/*
 * JHeuristics - The Java Meta-Heuritics Library
 * Copyright (C) 2004-2005, Universidade Federal de Campina Grande. All rights reserved.
 * 
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 * 
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 */
package ga.tsp;

import java.util.Iterator;

import utils.Graph;


public class GraphRouteEvaluator implements RouteEvaluator {
	private Graph graph;

	public GraphRouteEvaluator(Graph graph) {
		setGraph(graph);
	}

	public Object getInitialPosition() {
		Iterator it = graph.getNodes().iterator();
		return (it.hasNext() ? it.next() : null);
	}

	public Object getBestRoute(Object currentPosition, Object[] routes) {
		if (null == currentPosition) {
			// TODO: ERROR MSG
			throw new NullPointerException();
		}
		for (int i = 0 ; i < routes.length; i++) {
			if (null == routes[i]) {
				// TODO: ERROR MSG
				throw new NullPointerException();
			}
		}

		Object best = null;
		Comparable value = null;
		for (int i = 0; i < routes.length; i++) {
			if (null == best) {
				if (null != (value = (Comparable) graph.getWeigth(currentPosition, routes[i]))) {
					best = routes[i];
				}
			} else {
				Object otherValue = graph.getWeigth(currentPosition, routes[i]);
				if (null != otherValue) {
					if (value.compareTo(otherValue) > 0) {
						best = routes[i];
						value = (Comparable) otherValue;
					}
				}
			}
		}
		return best;
	}

	public Graph getGraph() {
		return graph;
	}

	public void setGraph(Graph graph) {
		if (null == graph) {
			// TODO: ERROR MSG
			throw new NullPointerException();
		}
		this.graph = graph;
	}

}
